package com.zero.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.zero.yygh.enums.PaymentStatusEnum;
import com.zero.yygh.enums.PaymentTypeEnum;
import com.zero.yygh.enums.RefundStatusEnum;
import com.zero.yygh.model.order.OrderInfo;
import com.zero.yygh.model.order.PaymentInfo;
import com.zero.yygh.model.order.RefundInfo;
import com.zero.yygh.order.config.ConstantProperties;
import com.zero.yygh.order.service.OrderService;
import com.zero.yygh.order.service.PaymentService;
import com.zero.yygh.order.service.RefundInfoService;
import com.zero.yygh.order.service.WeixinService;
import com.zero.yygh.order.utils.HttpClient;
import org.joda.time.DateTime;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zero
 * @desc
 * @create 2021/5/11
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Resource
    private OrderService orderService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private RefundInfoService refundInfoService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 根据订单号下单，生成支付链接
     * @param orderId 订单Id
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author zero
     * @date 2021/5/11 10:46
     */
    @Override
    public Map<String, String> createNative (Long orderId) {
        try{
            Map<String, String> payMap = (Map<String, String>) redisTemplate.opsForValue().get(orderId.toString());
            if (null != payMap) {
                return payMap;
            }
            // 根据id获取订单信息
            OrderInfo order = orderService.getById(orderId);
            // 保存交易信息
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            // 设置参数
            Map<String, String> paramMap = new HashMap<>(9);
            paramMap.put("appid", ConstantProperties.APPID);
            paramMap.put("mch_id", ConstantProperties.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = new DateTime(order.getReserveDate()).toString("MM-dd HH:mm") + "就诊" + order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            // TODO 金额修改
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");

            // 访问第三方接口并传递参数
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // 设置参数
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantProperties.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.post();
            // 获取返回的数据
            String xmlContent = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlContent);
            // 封装返回结果集
            Map<String, String> map = new HashMap<>(4);
            map.put("orderId", orderId.toString());
            map.put("totalFee", order.getAmount().toString());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));
            if(null != resultMap.get("result_code")){
                // 微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
            }
            return map;
        }catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    /**
     * 查询支付状态
     * @param orderId     订单id
     * @param paymentType 支付类型
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author zero
     * @date 2021/5/11 14:01
     */
    @Override
    public Map<String, String> queryPayStatus (Long orderId, String paymentType) {
        try {
            OrderInfo orderInfo = orderService.getById(orderId);
            //1、封装参数
            Map<String, String> paramMap = new HashMap<>(4);
            paramMap.put("appid", ConstantProperties.APPID);
            paramMap.put("mch_id", ConstantProperties.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantProperties.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据，转成Map
            String xml = client.getContent();
            //4、返回
            return WXPayUtil.xmlToMap(xml);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 退款操作
     * @param orderId 订单id
     * @return boolean
     * @author zero
     * @date 2021/5/12 10:43
     */
    @Override
    public boolean refund (Long orderId) {
        try{
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            Map<String,String> paramMap = new HashMap<>(8);
            //公众账号ID
            paramMap.put("appid",ConstantProperties.APPID);
            //商户编号
            paramMap.put("mch_id",ConstantProperties.PARTNER);
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            //微信订单号
            paramMap.put("transaction_id",paymentInfo.getTradeNo());
            //商户订单编号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo());
            //商户退款单号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo());
            // todo
            // paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            // paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String signedXml = WXPayUtil.generateSignedXml(paramMap, ConstantProperties.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(signedXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantProperties.PARTNER);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }
}